<?php

namespace addons\helper\controller\wxapp\auth;

use addons\helper\controller\wxapp\Base;

use app\admin\model\AuthGroup;
use fast\Tree;
use think\Db;
use think\Exception;

class Group extends Base
{
    protected $config = [
        'model'             => '角色组',
        'limit'             => 10,
        'defaultSort'       => 'id',
        'defaultOrder'      => 'desc',
        'tabField'          => '',
        'multi'             => true,
        'ruletreeUrl'       => 'auth.group/ruletree',
        'field' => [
            'pid'        => ['父级', 'select', false,  false, '', true, true, true],
            'name'       => ['名称', 'text', false,  false, '', true, true, true],
            'rules'      => ['权限', 'ruletree', false,  false, '', true, true, true],
            'createtime' => ['创建时间', 'datetime', false, false, '', true, false, false],
            'updatetime' => ['更新时间', 'datetime', false, false, '', true, false, false],
            'status'     => ['状态', 'select', false, false, '', true, true, true],
        ],
        'fieldContent' => [
            'pid'    => [],
            'status' => [
                'normal' => '正常',
                'hidden' => '隐藏'
            ]
        ],
        // [可选]前端表单验证规则
        'rules' => [
            'pid' => [
                'required'    => true
            ],
            'name' => [
                'required'    => true
            ],
            'rules' => [
                'required'    => true
            ]
        ],
        // [可选]前端表单自定义验证提示信息
        'rulesMessage' => [
            'rules' => [
                'required'    => '必须选择权限'
            ]
        ],
        'auth' => [
            'add'  => [
                'name' => '添加',
                'url'  => 'auth.group/add',
            ],
            'edit'  => [
                'name' => '编辑',
                'url'  => 'auth.group/edit',
            ],
            'multi' => [
                'del'  => [
                    'name'        => '删除',
                    'color'       => '#e74c3c',
                    'icon'        => 'fa-trash',
                    'url'         => 'auth.group/del'
                ]
            ],
            'more' => [
                'del'  => [
                    'name'  => '删除',
                    'color' => '#e74c3c',
                    'url'   => 'auth.group/del'
                ],
            ],
        ],
    ];

    protected $childrenGroupIds = [];
    protected $groupdata = [];
    protected $noNeedRight = ['ruletree'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\AuthGroup;
        $this->config['field'] = $this->formatField();
        $this->config['pk'] = $this->model->getPk() ? $this->model->getPk() : 'id';

        $this->childrenGroupIds = $this->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList,'pid','　');
        
        $result = [];
        if ($this->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        } else {
            $groups = $this->getGroups();
            foreach ($groups as $m => $n) {
                $result = array_merge($result, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
            }
        }
        
        $groupName = [];
        foreach ($result as $k => $v) {
            $groupName[($v['id'])] = $v['name'];
        }
        // 有顺序要求的select场景，须返回对象数组，避免顺序被js重排
        $fieldContentPid = [];
        foreach ($result as $k => $v) {
            $fieldContentPid[] = [
                $v['id'] => $v['name']
            ];
        }
        $this->groupdata = $groupName;
        $this->config['fieldContent']['pid'] = $fieldContentPid;
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $list = AuthGroup::all(array_keys($this->groupdata));
            $list = collection($list)->toArray();
            $groupList = [];
            foreach ($list as $k => $v) {
                $groupList[$v['id']] = $v;
            }
            $list = [];
            foreach ($this->groupdata as $k => $v) {
                if (isset($groupList[$k])) {
                    $groupList[$k]['name'] = $v;
                    $list[] = $groupList[$k];
                }
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            $data = [
                'tabList'  => null,
                'dataList' => $result,
                'config'   => $this->config
            ];
            $this->success('ok', $data);
        }
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('', [], 'strip_tags');
            $params['rules'] = explode(',', $params['rules']);
            if (!in_array($params['pid'], $this->childrenGroupIds)) {
                $this->error(__('The parent group exceeds permission limit'));
            }
            $parentmodel = $this->model->get($params['pid']);
            if (!$parentmodel) {
                $this->error(__('The parent group can not found'));
            }
            // 父级别的规则节点
            $parentrules = explode(',', $parentmodel->rules);
            // 当前组别的规则节点
            $currentrules = $this->getRuleIds();
            $rules = $params['rules'];
            // 如果父组不是超级管理员则需要过滤规则节点,不能超过父组别的权限
            $rules = in_array('*', $parentrules) ? $rules : array_intersect($parentrules, $rules);
            // 如果当前组别不是超级管理员则需要过滤规则节点,不能超当前组别的权限
            $rules = in_array('*', $currentrules) ? $rules : array_intersect($currentrules, $rules);
            $params['rules'] = implode(',', $rules);
            if ($params) {
                $this->model->allowField(true)->save($params);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    public function edit()
    {
        $ids = $this->request->get('ids');
        if (!in_array($ids, $this->childrenGroupIds)) {
            $this->error(__('You have no permission'));
        }
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('', [], 'strip_tags');
            //父节点不能是非权限内节点
            if (!in_array($params['pid'], $this->childrenGroupIds)) {
                $this->error(__('The parent group exceeds permission limit'));
            }
            // 父节点不能是它自身的子节点或自己本身
            if (in_array($params['pid'], Tree::instance()->getChildrenIds($row->id,true))){
                $this->error(__('The parent group can not be its own child or itself'));
            }
            $params['rules'] = explode(',', $params['rules']);

            $parentmodel = $this->model->get($params['pid']);
            if (!$parentmodel) {
                $this->error(__('The parent group can not found'));
            }
            // 父级别的规则节点
            $parentrules = explode(',', $parentmodel->rules);
            // 当前组别的规则节点
            $currentrules = $this->getRuleIds();
            $rules = $params['rules'];
            // 如果父组不是超级管理员则需要过滤规则节点,不能超过父组别的权限
            $rules = in_array('*', $parentrules) ? $rules : array_intersect($parentrules, $rules);
            // 如果当前组别不是超级管理员则需要过滤规则节点,不能超当前组别的权限
            $rules = in_array('*', $currentrules) ? $rules : array_intersect($currentrules, $rules);
            $params['rules'] = implode(',', $rules);
            if ($params) {
                Db::startTrans();
                try {
                    $row->allowField(true)->save($params);
                    $children_auth_groups = $this->model->all(['id'=>['in',implode(',',(Tree::instance()->getChildrenIds($row->id)))]]);
                    $childparams = [];
                    foreach ($children_auth_groups as $key=>$children_auth_group) {
                        $childparams[$key]['id'] = $children_auth_group->id;
                        $childparams[$key]['rules'] = implode(',', array_intersect(explode(',', $children_auth_group->rules), $rules));
                    }
                    $this->model->saveAll($childparams);
                    Db::commit();
                    $this->success();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error();
            return;
        }
        $this->success('ok',$row);
    }

    /**
     * 删除
     */
    public function del()
    {
        $ids = $this->request->post('ids/a');
        if ($ids) {
            $grouplist = $this->getGroups();
            $group_ids = array_map(function ($group) {
                return $group['id'];
            }, $grouplist);
            // 移除掉当前管理员所在组别
            $ids = array_diff($ids, $group_ids);

            // 循环判断每一个组别是否可删除
            $grouplist = $this->model->where('id', 'in', $ids)->select();
            $groupaccessmodel = model('app\admin\model\AuthGroupAccess');
            foreach ($grouplist as $k => $v) {
                // 当前组别下有管理员
                $groupone = $groupaccessmodel->get(['group_id' => $v['id']]);
                if ($groupone) {
                    $ids = array_diff($ids, [$v['id']]);
                    continue;
                }
                // 当前组别下有子组别
                $groupone = $this->model->get(['pid' => $v['id']]);
                if ($groupone) {
                    $ids = array_diff($ids, [$v['id']]);
                    continue;
                }
            }
            if (!$ids) {
                $this->error(__('You can not delete group that contain child group and administrators'));
            }
            $count = $this->model->where('id', 'in', $ids)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 组别禁止批量操作
        $this->error();
    }

    /**
     * 读取角色权限树
     *
     * @internal
     */
    public function ruletree()
    {
        $this->loadlang('auth/group');

        $id = $this->request->get('id');
        $pid = $this->request->get('pid');
        $parentGroupModel = $this->model->get($pid);
        $currentGroupModel = null;
        if ($id) {
            $currentGroupModel = $this->model->get($id);
        }
        if (($pid || $parentGroupModel) && (!$id || $currentGroupModel)) {
            $id = $id ? $id : null;
            $ruleList = collection(model('app\admin\model\AuthRule')->order('weigh', 'desc')->order('id', 'asc')->select())->toArray();
            //读取父类角色所有节点列表
            $parentRuleList = [];
            if (in_array('*', explode(',', $parentGroupModel->rules))) {
                $parentRuleList = $ruleList;
            } else {
                $parentRuleIds = explode(',', $parentGroupModel->rules);
                foreach ($ruleList as $k => $v) {
                    if (in_array($v['id'], $parentRuleIds)) {
                        $parentRuleList[] = $v;
                    }
                }
            }
            $ruleTree = new Tree();
            $groupTree = new Tree();
            //当前所有正常规则列表
            $ruleTree->init($parentRuleList,null,' ');
            //角色组列表
            $groupTree->init(collection($this->model->where('id', 'in', $this->childrenGroupIds)->select())->toArray());

            if (!$id || !in_array($pid, $this->childrenGroupIds) || !in_array($pid, $groupTree->getChildrenIds($id, true))) {
                $this->success('',$ruleTree->getTreeArray(0));
            } else {
                $this->error(__('Can not change the parent to child'));
            }
        } else {
            $this->error(__('Group not found'));
        }
    }
}
